package xyz.zhno.mall.common.web.handler;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import xyz.zhno.mall.common.core.vo.ResultVO;
import xyz.zhno.mall.common.web.util.JSONUtils;

/**
 * Controller统一响应处理
 * @author zh_o
 */
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
public class ControllerResponseHandler implements ResponseBodyAdvice<Object> {

    /**
     * 需要处理的返回值
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> aClass) {
        // 如果返回值已经是统一响应实体，则不需要处理
        return !returnType.getParameterType().equals(ResultVO.class);
    }

    /**
     * 处理返回值
     */
    @Override
    public Object beforeBodyWrite(Object obj, MethodParameter returnType, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        // 处理字符串类型
        if (returnType.getParameterType().equals(String.class)) {
            return JSONUtils.toJsonStr(ResultVO.success("success", obj));
        }
        // 其他类型
        return ResultVO.success(obj);
    }

}
